#!/usr/bin/env python
# -*- coding:utf-8 -*-

import binascii


command = [0]*11
command[0] = 0x02 #start mark
command[1] = 0x30 #query cmd

command[2] = 0x31    #paddress
command[3] = 0x30
command[4] = 0x31
command[5] = 0x30

command[6] = 0x30 #constant data
command[7] = 0x32 #counts for read

command[8] = 0x03
#ABCDH
def set_data_address(addr):
	command[2] = ord(str(hex(addr/0x1000))[2:].upper())
	command[3] = ord(str(hex(addr%0x1000/0x100))[2:].upper())
	command[4] = ord(str(hex(addr%0x100/0x10))[2:].upper())
	command[5] = ord(str(hex(addr%0x10))[2:].upper())

def cs_data_len(data_len):
	command[6] = ord(str(hex(data_len/0x10))[2:].upper())
	command[7] = ord(str(hex(data_len%0x10))[2:].upper())
	#print hex(command[6])
	#print hex(command[7])

# cal the chk number.get the last two number
def cs_chk_data():
	CHK = 0
	for i in range(1, 9):
		CHK += command[i] 
	print CHK
	print hex(CHK)
	print hex(CHK%0x100)
	command[9]  = ord(str(hex(CHK%0x100/0x10))[2:].upper().upper())
	command[10] = ord(str(hex(CHK%0x10))[2:].upper())
	print command

set_data_address(0x1000)
cs_data_len(2)
cs_chk_data()


import binascii
print binascii.hexlify(bytearray(command))

#cmd = bytearray(command)
#com = serial.serial('com2')
#com.write(cmd)


response = [
0x20, 
0x30, 
0x31,
0x30, 
0x30, 
0x03, 
0x43, 
0x34]
print binascii.hexlify(bytearray(response))
data = int(chr(response[1]))*0x10 
data += int(chr(response[2])) 
data += int(chr(response[3]))*0x1000
data += int(chr(response[4]))*0x100
#data = int(chr(response[1])*0x1+response[2]
#response[3]*0x100+response[4]*0x10
def response_chk():
	chk = 0
	for i in range(1, 6):
		chk += response[i]
	print chk
	print hex(chk)
	print response[6]
	print response[7]
	if ord(str(hex(chk%0x100/0x10))[2:].upper()) == response[6]:
		print "hw chk ok!"
	else:
		print "hw chk failed!"

	if ord(str(hex(chk%0x100%0x10))[2:].upper()) == response[7]:
		print "lw chk ok!"
	else:
		print "lw chk failed!"

response_chk()
print hex(data)

